import React from 'react';
import { connect } from 'dva';
// import { Redirect } from 'dva/router';
import { withRouter, Redirect } from 'umi';
import { Avatar, Col, Dropdown, Icon, Layout, Menu, Row, message, Spin } from 'antd';

import SiderMenu from '@/components/sider_menu/SiderMenu';
import StorageUtils from '@/utils/StorageUtils';
import StringUtils from '@/utils/StringUtils';
import { SESSION } from '@/constants/ModelNamespaces'
import styles from './homeLayout.less';
import LoginLayout from './LoginLayout';
// import { GameResTypes } from '@/pages/store/game_res';

const { Header, Content } = Layout;

interface HomeLayoutProps{
    sessionState:any;
    // gameResState:any;
    match:any;
    location:any;
    // history:any;
    dispatch:Function;
    logout:Function;
}
/**
 * 布局类.按照路由配置,pages下的页面会自动加载到Content标签下.
 */
class HomeLayout extends React.Component<HomeLayoutProps,any> {
  constructor(props:HomeLayoutProps){
    super(props);

    this.state = {
      collapsed: false
    }
  }
  componentDidMount() {
    //TODO:由于加载配置很关键,后面很多地方依赖这块.这里显示一个同步loading,不loading完不允许用户进一步操作.
    // this.props.dispatch({ type: GameResTypes.GET_GAME_RES_CONFIG });
  }

  //折叠侧边栏
  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed
    });
  }

  //处理顶部用户菜单的点击
  handleMenuClick = ({ key }) => {
    if (key === 'triggerError') {
      //执行相关操作.
      message.info('xxx操作', 2);
      return;
    }
    if (key === 'logout') {
      this.props.logout();
    }
  }

  render() {
    //如果访问的是登录页面,则使用基本布局.
    if(this.props.location.pathname === '/session'){
      return (<LoginLayout>{this.props.children}</LoginLayout>);
    }

    //检查会话是否有效.先从store中获取session,再从浏览器sessionStorage中获取.都获取不到,视为已注销或者尚未登录.
    let storeSession = this.props.sessionState.session;
    let localSession = StorageUtils.getSessionItem('session')||{};

    let session = StringUtils.isNotBlank(storeSession.session_id) ? storeSession : localSession;

    let isLogined = StringUtils.isNotBlank(session.session_id);
    if (!isLogined) {
      return (<Redirect to="/session" />);
    }
    
    const menu = (
      <Menu className="header-user-menu" selectedKeys={[]} onClick={this.handleMenuClick}>
        <Menu.Item disabled={true} ><Icon type="user" />个人中心</Menu.Item>
        <Menu.Item disabled={true} ><Icon type="setting" />设置</Menu.Item>
        {/* <Menu.Item key="triggerError"><Icon type="close-circle" />触发报错</Menu.Item> */}
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
      </Menu>
    );

    let body = (
      <Layout>
        <SiderMenu
          trigger={null}
          collapsed={this.state.collapsed}
          match={this.props.match}
        />
        <Layout>
          <Header>
            <Row justify="start" align="middle" style={{ 'width': '100%' }}>
              <Col span={4}>
                {/* <Button type="default" onClick={this.toggleCollapsed} size="small" className={styles['collapse-btn']}> */}
                <Icon
                  type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                  onClick={this.toggle}
                  className={styles.trigger}
                />
                {/* </Button> */}
              </Col>
              <Col span={16} />
              <Col span={4}>
                <div className={styles['header-userMenu']}>
                  <Dropdown overlay={menu}>
                    <span>
                      <Avatar shape="square" src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                      <span>&nbsp;&nbsp;{session.display_name != null ? session.display_name : ''}&nbsp;&nbsp;</span>
                    </span>
                  </Dropdown>
                </div>
              </Col>
            </Row>
          </Header>
          <Content>
            {this.props.children}
          </Content>
        </Layout>
      </Layout>
    );

    // let isResLoaded = this.props.gameResState.imageResConfigs.length > 0;

    // if(isResLoaded){
    //   return body;
    // }else{
    //   return (
    //   <div style={{ height:"100%",width:"100%",display:"flex",justifyContent:"center",flexDirection:"column",alignItems:"center" }}>
    //     <span>正在加载初始资源...</span>
    //     <Spin size="large" spinning={true} />
    //   </div>);
    // }

    return body;
  }

}

//********************************** 容器组件 ********************************** 

const sessionNamespace = SESSION;

const mapStateToProps = state => {
  return {
    // state: state,
    sessionState: state[sessionNamespace],
    // gameResState: state.GameResReducer,
  };
}
const mapDispatchToProps = dispatch => {
  return {
    dispatch: dispatch,
    logout:()=>{
      dispatch({type:`${sessionNamespace}/logout`});
    }
  }
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(HomeLayout));


